package zheezes.util;

import java.nio.ByteBuffer;

/**
 * @author hcconquer@gmail.com
 */
public class ZBuffer {
	/**
	 * must flip youself return the end of the line
	 */
	public static int findNewLine(ByteBuffer buf, int pos) {
		byte b = 0;
		while (pos < buf.limit()) {
			b = buf.get(pos);
			if (b == '\r' || b == '\n') {
				break;
			}
			pos++;
		}
		if (pos >= buf.limit()) {
			return -1;
		}
		return pos;
	}

	public static int findNewLine(ByteBuffer buf) {
		return findNewLine(buf, buf.position());
	}

	/**
	 * return the begin not '\r' '\n'
	 */
	public static int skipNewLine(ByteBuffer buf, int pos) {
		byte b = 0;
		while (pos < buf.limit()) {
			b = buf.get(pos);
			if (b != '\r' && b != '\n') {
				break;
			}
			pos++;
		}
		return pos;
	}

	public static int skipNewLine(ByteBuffer buf) {
		return skipNewLine(buf, buf.position());
	}

	public static byte[] readLine(ByteBuffer buf) {
		int pos = 0;
		pos = ZBuffer.findNewLine(buf);
		if (pos < buf.position()) {
			return null;
		}
		int len = pos - buf.position();
		byte[] line = null;
		line = getBytes(buf, len);

		pos = ZBuffer.skipNewLine(buf);
		buf.position(pos);
		return line;
	}

	public static byte[] readLastLine(ByteBuffer buf) {
		byte[] line = null, last = null;
		while ((line = readLine(buf)) != null) {
			last = line;
		}
		return last;
	}

	public static byte[] getBytes(ByteBuffer buf, int off, int len) {
		if ((off | len) < 0) {
			return null;
		}
		if (len > buf.remaining()) {
			return null;
		}
		byte[] res = new byte[len];
		for (int i = 0; i < len; i++) {
			res[i] = buf.get(off + i);
		}
		buf.position(buf.position() + len);
		return res;
	}

	public static byte[] getBytes(ByteBuffer buf, int len) {
		return getBytes(buf, buf.position(), len);
	}
}
